package com.github.browep.bat.activities;

import android.app.AlertDialog;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.github.browep.bat.R;
import com.github.browep.bat.ScreenService;
import com.github.browep.bat.util.DistanceUtil;
import com.github.browep.bat.util.UiUtilities;
import org.w3c.dom.Element;

import java.text.NumberFormat;
import java.util.Comparator;
import java.util.List;

import static com.github.browep.bat.Constants.SCREEN_ID;
import static com.github.browep.bat.util.XmlUtil.*;
import static java.util.Collections.sort;

/**
 * Created by IntelliJ IDEA.
 * User: paul
 * Date: 8/28/11
 * Time: 3:28 PM
 * To change this template use File | Settings | File Templates.
 */
public class Locations extends BaseActivity {
    public static final String LOG_TAG = Locations.class.getSimpleName();

    // Number formatter for floating-point values.
    private static NumberFormat floatFormat = null;

    static {
        // Set up the number formatter for floating-point values.
        floatFormat = NumberFormat.getInstance();
        floatFormat.setMaximumFractionDigits(1);
    }

    private String screenId;
    private ScreenService.Screen screen;
    private String defaultName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupWrappedUI(R.layout.locations);
        screenId = (String) getIntent().getExtras().get(SCREEN_ID);

        screen = getScreenService().getScreenById(screenId);
        Element locationsElement = getElementByTagName(screen.getScreenElement(), "locations");
        defaultName = getElementByTagName(locationsElement, "default-name").getTextContent().trim();

        List<Element> locationElems = getChildElementListWithTag(locationsElement, "location");

        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        final Location lastKnownLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        if (lastKnownLocation != null) {
            sort(locationElems, new Comparator<Element>() {
                public int compare(Element element1, Element element2) {
                    return Double.compare(distanceToAddress(lastKnownLocation, element1),
                            distanceToAddress(lastKnownLocation, element2));
                }
            });
        }

        ListView listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(new LocationArrayAdapter(locationElems));
        listView.setOnItemClickListener(onItemClickListener);


    }

    private ListView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapterView, final View view, int i, long l) {
            final Object phone = view.getTag(R.id.phone);
            final Object lng = view.getTag(R.id.lng);
            final Object lat = view.getTag(R.id.lat);
            final String address = (String) view.getTag(R.id.address);
            final String hours = (String) view.getTag(R.id.hours);
            final Context context = self;

            AlertDialog alertDialog = UiUtilities.locationMultiPopup(phone, lng, lat, address, hours, context);
            alertDialog.show();
        }
    };


    public class LocationArrayAdapter extends BaseAdapter {

        private List<Element> locations;

        public LocationArrayAdapter(List<Element> locations) {
            this.locations = locations;
        }

        public int getCount() {
            return locations.size();
        }

        public Object getItem(int i) {
            return locations.get(i);
        }

        public long getItemId(int i) {
            return i;
        }


        public View getView(int i, View view, ViewGroup viewGroup) {
            if (view == null) {
                view = LayoutInflater.from(Locations.this).inflate(R.layout.location_row, viewGroup, false);
                TextView nameTextView = (TextView) view.findViewById(R.id.location_name);
                Element locationElement = (Element) getItem(i);

                // name
                Element name = getElementByTagName(locationElement, "name");
                if (name != null)
                    nameTextView.setText(name.getTextContent().trim());
                else {
                    nameTextView.setText(Locations.this.defaultName);
                }

                // location
                Element addressElement = getElementByTagName(locationElement, "address");
                TextView addressTextView = (TextView) view.findViewById(R.id.location_text);
                String address = addressElement.getTextContent().trim();
                view.setTag(R.id.address, address);

                addressTextView.setText(address);

                // phone
                Element phoneElement = getElementByTagName(locationElement, "phone");
                TextView phoneTextView = (TextView) view.findViewById(R.id.location_phone);
                String phone = phoneElement.getTextContent().trim();
                view.setTag(R.id.phone, phone);
                phoneTextView.setText(phone);

                // lat lng
                view.setTag(R.id.lat, getChildTextContent(locationElement, "lat"));
                view.setTag(R.id.lng, getChildTextContent(locationElement, "lng"));

                // hours
                if (getElementByTagName(locationElement, "hours") != null) {
                    String hours = getChildTextContent(locationElement, "hours");
                    if (hours != null)
                        view.setTag(R.id.hours, hours);
                }

                if (locationElement.hasAttributeNS("tmp", "distance")) {
                    ((TextView) view.findViewById(R.id.location_distance))
                            .setText(floatFormat.format(
                                    Double.valueOf(locationElement.getAttributeNS("tmp", "distance"))) + " mi");
                }


            }
            return (view);

        }
    }

    private static double distanceToAddress(Location location, Element locationElem) {
        if (locationElem.hasAttributeNS("tmp", "distance"))
            return Double.valueOf(locationElem.getAttributeNS("tmp", "distance"));
        double lat1 = Double.valueOf(getChildTextContent(locationElem, "lat"));
        double lng1 = Double.valueOf(getChildTextContent(locationElem, "lng"));


        double distance = DistanceUtil.distanceInMiles(lat1, lng1, location.getLatitude(), location.getLongitude());
        locationElem.setAttributeNS("tmp", "distance", String.valueOf(distance));
        return distance;


    }
}

